class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  # protect_from_forgery with: :exception

  before_action :authenticate_wechat_user!


  protected

  #获取当前session_id
  def current_wechat_session

    redirect_uri = CGI::escape("#{RestConfig::WX_HOST}sign_in")

    @wechat_session ||= WechatSession.where(:openid => session[:openid]).first

    if !@wechat_session.present? || !@wechat_session.openid.present? || !@wechat_session.access_token.present?

      redirect_to "https://open.weixin.qq.com/connect/oauth2/authorize?appid=#{Wechat.config.appid}&redirect_uri=#{redirect_uri}&response_type=code&scope=snsapi_userinfo&state=12356#wechat_redirect"
      return
    end

    # 失效的话，更新微商城
    if ((Time.zone.now-@wechat_session.updated_at) > 7000) && @wechat_session.refresh_token.present?

      #根据code获取openId
      result = Wechat.api.web_refresh_access_token(@wechat_session.refresh_token)
      Rails.logger.info "微信认证结果为：#{result.to_json}"
      if !result['access_token'].present?
        redirect_to "https://open.weixin.qq.com/connect/oauth2/authorize?appid=#{Wechat.config.appid}&redirect_uri=#{redirect_uri}&response_type=code&scope=snsapi_userinfo&state=12356#wechat_redirect"
        return
      end
      @wechat_session.access_token = result['access_token']
      @wechat_session.refresh_token = result['refresh_token']
      @wechat_session.save
    end

    @wechat_session
  end

  #获取当前session_id
  def current_userinfo

    @userinfo ||= Userinfo.find(session[:userinfo_id])
  end

  def authenticate_wechat_user!


    Rails.logger.info "认证过滤：openid#{session[:openid]}，userinfo_id：#{session[:userinfo_id]}"

    redirect_uri = CGI::escape("#{RestConfig::WX_HOST}sign_in")
    @wechat_session ||= WechatSession.where(:openid => session[:openid]).first
    #微信未授权
    if !@wechat_session.present? || !@wechat_session.openid.present? || !@wechat_session.access_token.present? || !session[:openid].present?
      redirect_to "https://open.weixin.qq.com/connect/oauth2/authorize?appid=#{Wechat.config.appid}&redirect_uri=#{redirect_uri}&response_type=code&scope=snsapi_userinfo&state=12356#wechat_redirect"
      return
    end

    #定位未成功
    if !session[:userinfo_id].present?
      redirect_to '/get_location'
      return
    end
  end

  def authenticate_location!

    Rails.logger.info "定位认证！session_id:#{session.id}"

    if !RootHelper.is_location_expire(session.id) || !session[:userinfo_id].present?
      Rails.logger.info "定位认证失败，重新定位！"
      RootHelper.clean_location(session.id)
      redirect_to "/refresh_location"
      return
    end
  end


  def get_service_params
    params.to_hash
  end

end
